<template>
  <el-dialog class="departmentDialog" :visible.sync="visible" :title="dataForm.userId?'编辑':'新增'" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form size="small" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submit()" label-width="120px">
      <el-form-item label="部门名称" prop="roleName">
        <el-input class="s_input" v-model="dataForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input class="s_input" v-model="dataForm.remark"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button size="small" @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button size="small" type="primary" @click="submit()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
      dataForm: {}
    }
  },
  computed: {
    dataRule () {
      return {
        roleName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 显示弹窗
    init (row) {
      this.visible = true
      if (row) {
        this.dataForm = JSON.parse(JSON.stringify(row))
      } else {
        this.dataForm = {
          roleId: '',
          roleName: '',
          remark: ''
        }
      }
      console.log(this.dataForm)
    },
    // 表单提交
    submit: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http.post('/sys/role/' + (this.dataForm.roleId ? 'update' : 'save'), this.dataForm).then(({ data: res }) => {
          if (res.code === 0) {
            this.$message.success('保存成功!')
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$message.error(res.msg)
          }
        }).catch((error) => {
          return this.$message.error(error)
        })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss">
.departmentDialog{
  .el-dialog__header{
    .el-dialog__title{
      font-size: 14px;
      font-weight: bold;
    }
    border-bottom: 1px solid #f2f2f2;
  }
  .el-dialog__body{
    padding: 15px 20px;
  }
  .s_input{
    width: 80%;
    margin-right: 10px;
  }
}
</style>
